package com.topisv.tms.web.stock.outstorage;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.stock.ViewCusStock;
import com.topisv.tms.entity.stock.instorage.InstorageBill;
import com.topisv.tms.entity.stock.oustorage.OutstorageBill;
import com.topisv.tms.entity.stock.oustorage.OutstorageBillItem;
import com.topisv.tms.mybatis.Pagination;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.ViewCusStockService;
import com.topisv.tms.service.stock.instorage.InstorageBillService;
import com.topisv.tms.service.stock.outstorage.OutstorageBillItemService;
import com.topisv.tms.service.stock.outstorage.OutstorageBillService;
import com.topisv.tms.service.task.WorkOrderResendService;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.vo.interfacetask.WorkOrderResendVo;
import com.topisv.tms.web.base.BaseDataTableController;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 出库单_control
 * @author ch
 */
@Controller
@RequestMapping(value = "/outstorageBill")
public class OutstorageBillController extends BaseDataTableController{

	private static final Logger logger = LoggerFactory.getLogger(OutstorageBillController.class);
	private static final int PAGE_SIZE = 30;

	@Autowired
	private InstorageBillService instorageBillService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areagroupService;
	@Autowired
	private ViewCusStockService viewCusStockService;
	@Autowired
	private OutstorageBillService outstorageBillService;
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private WorkOrderResendService workOrderResendService;
	
	@RequestMapping(value = "v2_show")
	public String show(Model model){
		fillSelectValue(model, null);
		List<AreaGroup> warehouseList1 = null;
		warehouseList1 = areagroupService.loadByWarehouseType(StatusEnums.user_type_paiu.getStatus());
		model.addAttribute("warehouseList1", warehouseList1);
		return "stock/outstorage/outstorageBillList";
	}
	
	/**
	 * 查询商品
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "page")
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			Map<String, Object> searchParams = paramHolder.getSearchParams();
			String fromTm = (String)searchParams.get("GTE_createTime");
			String toTm = (String)searchParams.get("LT_createTime");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(!StringUtils.isBlank(fromTm)){
				searchParams.put("GTE_createTime",sdf.parse(fromTm));
			}
			if(!StringUtils.isBlank(toTm)){
				searchParams.put("LT_createTime",sdf.parse(toTm));
			}
			// 查询商品
			Page<OutstorageBill> page = outstorageBillService.loadPageByParam(paramHolder);
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			logger.error("error",e);
		}
	}
	
	/**
	 * 导向出库单列表页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toOutstorageBillListPage")
	public String toOutstorageBillListPage(Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//如果是paiu用户,初始化数据
			if("paiu".equals(curUser.userType)){
			    //查询出库单
				Map<String, Object> param =new HashMap<String, Object>();
				param.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
				param.put("status", "1");
				Page<OutstorageBill> page =this.outstorageBillService.loadPageByParam(param,1, PAGE_SIZE);
				model.addAttribute("page", page);
				model.addAttribute("status",1);
			}
			
			
			//如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=curUser.customerCode;
				model.addAttribute("customerCode", customerCode); 
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areagroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//查询出库单
				Map<String, Object> param =new HashMap<String, Object>();
				param.put("customerCodes", customerCode);
				param.put("status", "1");
				Page<OutstorageBill> page =this.outstorageBillService.loadPageByParam(param,1, PAGE_SIZE);
				model.addAttribute("page", page);
				model.addAttribute("status",1);
			}
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/outstorage/outstorageBillList";
	}
	
	/**
	 * 查询入库单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryBill")
	public String queryBill(Model model, ServletRequest request) {
		try {
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//查询出库单
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			
			String fromDateStr=(String) param.get("fromDate");
			String toDateStr=(String) param.get("toDate");
			Date fromDate=null;
			Date toDate=null;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(StringUtils.isNotEmpty(fromDateStr)){
				fromDate=sdf.parse(fromDateStr+" 00:00:00");
			}
			if(StringUtils.isNotEmpty(toDateStr)){
				toDate=sdf.parse(toDateStr+" 23:59:59");
			}
			param.put("fromDate", fromDate);
			param.put("toDate", toDate);
			
			
			Page<OutstorageBill> page =this.outstorageBillService.loadPageByParam(param,1, PAGE_SIZE);
			model.addAttribute("page", page);
			model.addAttribute("param", param);
			
			//初始化仓库数据
			String customerCode=(String) param.get("customerCode");
			if(customerCode!=null){
			   List<AreaGroup> warehouseList=this.areagroupService.loadAreaGroupByAuthority(curUser, customerCode);
			   model.addAttribute("warehouseList", warehouseList); 
			}
			  
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/outstorage/outstorageBillList";
	}
	
	/**
	 * 导向创建调拨出库单页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toCreateBill/{billType}")
	public String toCreateBill(@PathVariable("billType") String billType,Model model, ServletRequest request) {
		try {
			
			//区分出库类型
			String typeName="";
			if("allot".equals(billType)){
				typeName="调拨";
			}else if("sale".equals(billType)){
				typeName="销售";
			}else if("return".equals(billType)){
				typeName="返仓";
			}else if("bad_return".equals(billType)){
				typeName="次品返仓";
			}
			model.addAttribute("billType",billType);
			model.addAttribute("typeName",typeName);
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//如果是paiu用户,初始化数据
			if("paiu".equals(curUser.userType)){
			    
			    //查询出库单
				Map<String, Object> param =new HashMap<String, Object>();
				param.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
				param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
				param.put("status", "1");
				List<InstorageBill> billList = this.instorageBillService.loadByParam(param);
				model.addAttribute("billList", billList);
				model.addAttribute("status",1);
			}
			
			
			//如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=curUser.customerCode;
				model.addAttribute("customerCode", customerCode); 
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areagroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//查询入库单
				Map<String, Object> param =new HashMap<String, Object>();
				param.put("customerCode", customerCode);
				param.put("status", "1");
				List<InstorageBill> billList = this.instorageBillService.loadByParam(param);
				model.addAttribute("billList", billList);
			}
			List<AreaGroup> warehouseList1 = null;
			warehouseList1 = areagroupService.loadByWarehouseType(StatusEnums.user_type_paiu.getStatus());
			model.addAttribute("warehouseList1", warehouseList1);
			
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "stock/outstorage/outstorageBillCreate";
	}
	
	/**
	 * 删除入库单
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "ajaxDelete")
	@ResponseBody
	public String ajaxDelete(ServletRequest request) {
		try {
			Long billId=Long.valueOf(request.getParameter("billId"));
			this.instorageBillService.deleteBill(billId);
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}
	}
	
	
	/**
	 * 修改入库单信息
	 * @param bill
	 * @param redirectAttributes
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid InstorageBill bill, RedirectAttributes redirectAttributes){
		
		InstorageBill _bill=this.instorageBillService.loadBillById(bill.getId());
		_bill.setBoxNum(bill.getBoxNum());
		_bill.setSkuNum(bill.getSkuNum());
		_bill.setGoodsNum(bill.getGoodsNum());
		_bill.setRemarks(bill.getRemarks());
		_bill.setAboutCode(bill.getAboutCode());
		
		this.instorageBillService.saveBill(_bill);
		return "redirect:/cusInstorageBill";
	}
	
	/**
	 * ajax查询商品
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ajaxQuerySku")
	public String ajaxQuerySku(ServletRequest request,HttpServletResponse response) {
		try {	
			String  customerCode=request.getParameter("customerCode");
			String  warehouseCode=request.getParameter("warehouseCode");
			String  sku=request.getParameter("sku");
			
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("customerCode", customerCode);
			param.put("warehouseCode", warehouseCode);
			param.put("sku", sku);
			List<ViewCusStock> stockList=this.viewCusStockService.loadByParam(param);
			
			JSONObject json = new JSONObject();
			json.put("stockList", stockList);
			PrintWriter out = response.getWriter();
			out.print(json);
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return null;
	}
	
	
	/**
	 * 创建出库单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCreateBill")
	@SuppressWarnings("unchecked")
	public void ajaxCreateBill(ServletRequest request,HttpServletResponse response) {
		try {	
			
			String customerCode=request.getParameter("customerCode"); 
			String warehouseCode_out=request.getParameter("warehouseCode_out"); 
			String warehouseCode_in=request.getParameter("warehouseCode_in"); 
			String billType=request.getParameter("billType"); 
			String jsonText=request.getParameter("jsonText");
			JSONArray infoArray = JSONArray.fromObject(jsonText);
			
			Map<String, Integer> infoMap=new HashMap<String, Integer>();
			for (Object info : infoArray) {
				Map<String, Object> map=(Map<String, Object>)info;
				String sku=(String)map.get("sku");
				Integer num=Integer.valueOf(map.get("num")+"");
				infoMap.put(sku, num);
			}
			
			String result=this.outstorageBillService.createBill(customerCode,warehouseCode_out,warehouseCode_in,infoMap,billType);
			
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("result", result);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
	}
	
	@Autowired
	private OutstorageBillItemService outstorageBillItemService;
	
	/**
	 * 导向出库单明细页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toOutstorageBillDetailPage/{billCode}")
	public String toOutstorageBillListPage(@PathVariable("billCode")String billCode,Model model) {
		try {
			 List<OutstorageBillItem> itemList=this.outstorageBillItemService.loadByBillCode(billCode);
			 model.addAttribute("itemList", itemList);
			 
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "stock/outstorage/outstorageBillDetail";
	}
	

	/**
	 * 跳转到--已发货订单重新回传页面
	 *
	 * @param 
	 * @return 
	 * @throws 
	 * @author "yuansheng"
	 * @version 1.0.0
	 */
	@RequestMapping(value = "v2_outstorageBillQMResend")
	public String toOutstorageBillQMResend(Model model, ServletRequest request) {
	  //查出当前用户关联的商家列表
        ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
        model.addAttribute("customerList",customerList);
        //如果是商家用户,初始化数据
        /*if(StatusEnums.user_type_customer.getStatus().equals(curUser.userType)){
            String customerCode=customerList.get(0).getCustomerCode();
            model.addAttribute("customerCode", customerCode);
            //初始化仓库数据
            List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
            model.addAttribute("warehouseList", warehouseList);
        }else if(StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)){
            List<AreaGroup> warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
            model.addAttribute("warehouseList", warehouseList);
        }*/
        return "stock/outstorage/outstorageBillQMResend";
	}
	
	/**
	 * 分页查询已发货订单
	 *
	 * @param 
	 * @return 
	 * @throws 
	 * @author yuansheng
	 * @version 1.0.0
	 */
	@ResponseBody
    @RequestMapping(value="queryQMResendInfo") 
	//@RequestBody JSONParam[] paramJsodn,HttpServletRequest request, HttpServletResponse response
    public Object queryQMResendInfo(WorkOrderResendVo vo) {
	    Pagination page = null;
	    try {
	        page = workOrderResendService.getPageWorkOrderResend(vo);
        } catch (Exception e) {
            logger.info("queryQMResendInfo error", e);
        }
	    return page;
   }
	
	/**
	 * 已发货订单重新回传
	 *
	 * @param 
	 * @return 
	 * @throws 
	 * @author "yuansheng"
	 * @version 1.0.0
	 */
	@ResponseBody
	@RequestMapping(value = "outstorageBillQMResend")
    public Map<String, Object> outstorageBillQMResend(@RequestParam(value = "orderNos[]") String[] orderNos, @RequestParam(value = "customerCodes[]") String[] customerCodes) {
	    Map<String, Object> result = new HashMap<String, Object>();
	    try {
	        result = outstorageBillService.outstorageBillQMResend(orderNos, customerCodes);
	        result.put("state", "success");
        } catch (Exception e) {
            log.info("已发货订单重新回传", e);
            result.put("state", "failure");
            result.put("msg", "回传失败，请稍后再试");
        }
        return result;
	}
	
	
}
